package com.zhangyj.impl.actions;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhangyj.action.AbstractAction;
import com.zhangyj.action.RequestAction;
import com.zhangyj.action.RequestMethod;
import com.zhangyj.action.ResponseResultType;
import com.zhangyj.dao.DaoManager;
import com.zhangyj.data.BEntMapper;
import com.zhangyj.data.tables.BEnt;
import com.zhangyj.db.DBUtil;
import com.zhangyj.impl.ViewName;
import com.zhangyj.security.Permission;
import com.zhangyj.util.Tools;

@RequestAction(name = "ent")
public class EntAction extends AbstractAction {
	Logger log = LoggerFactory.getLogger(RoleAction.class);
	private static final long serialVersionUID = -5429006160721387547L;

	@RequestMethod(name = "index", result = ResponseResultType.PATH)
	public String index() throws Exception {
		this.validatePermission(Permission.VIEW);
		return ViewName.ENT_INDEX;
	}

	@RequestMethod(name = "list")
	public void list() throws Exception {
		this.validatePermission(Permission.VIEW);
		List<BEnt> list = DBUtil.queryList(" select *  from b_ent where deleted = 0  order by ent_id LIMIT ? OFFSET ?", BEnt.class, getIntParameter("start", 0), getIntParameter("count", 50));
		writerBackJSON(Tools.object2jsonStr(list, "entId", list.size()));
	}

	@RequestMethod(name = "load")
	public void load() throws Exception {
		this.validatePermission(Permission.VIEW);
		BEnt ent = null;
		int entid = getIntParameter("entid");
		SqlSession ss = DaoManager.getSqlSession();
		try {
			BEntMapper mapper = ss.getMapper(BEntMapper.class);
			ent = mapper.selectByPrimaryKey(entid);
		} finally {
			ss.close();
		}
		writerBackJSON(Tools.object2jsonStr(ent));
	}

	@RequestMethod(name = "save")
	public void save() throws Exception {
		String oper = this.getParameter("oper");
		BEnt ent = new BEnt();
		BeanUtils.populate(ent, new HashMap<String, String>(request.getParameterMap()));
		Connection db = DBUtil.getConnection();
		try {
			if ("add".equals(oper)) {
				DBUtil.begnTrans();
				ent.setEntId(DBUtil.getIntId(db, "b_ent"));
				SqlSession ss = DaoManager.getSqlSession(db);
				BEntMapper mapper = ss.getMapper(BEntMapper.class);
				mapper.insert(ent);
				DBUtil.commit();
			} else if ("mod".equals(oper)) {
				SqlSession ss = DaoManager.getSqlSession(db);
				BEntMapper mapper = ss.getMapper(BEntMapper.class);
				mapper.updateByPrimaryKey(ent);
			}
			success("", ent);
		} catch (Exception e) {
			DBUtil.rollback();
			log.error("存盘:" + e.getMessage());
			fail(e);
		} finally {
			DBUtil.close();
		}
	}

}
